﻿using System.Transactions;
using AutoMapper;
using MediatR;
using Provenance.Domain.User;
using Provenance.ErrorCount;
using Provenance.Infra.Interfaces.User;
using Provenance.Write.Api.Application.Command.User;

namespace Provenance.Write.Api.Application.CommandHandler.User
{
    public class InsertRoleCommandHandler : IRequestHandler<InsertRoleCommand, ApiResult>
    {
        private readonly IRoleRepository _roleRepository;
        private readonly IRolePermissionRepository _rolePermissionRepository;
        private readonly IMapper _mapper;
        private readonly ILogger<InsertRoleCommandHandler> _logger;
        public InsertRoleCommandHandler(IRoleRepository roleRepository, IRolePermissionRepository rolePermissionRepository, IMapper mapper, ILogger<InsertRoleCommandHandler> logger)
        {
            _roleRepository = roleRepository;
            _rolePermissionRepository = rolePermissionRepository;
            _mapper = mapper;
            _logger = logger;
        }

        public async Task<ApiResult> Handle(InsertRoleCommand request, CancellationToken cancellationToken)
        {
            try
            {
                using (var tran = new TransactionScope(TransactionScopeAsyncFlowOption.Enabled))
                {
                    try
                    {
                        var role = _mapper.Map<Role>(request);
                        await _roleRepository.InsertEntity(role);
                        string[] stringIds = request.PermissionIds.Split(",");
                        int[] IntIds = stringIds.Select(x => int.Parse(x)).ToArray();
                        var list = new List<RolePermission>();
                        foreach (var id in IntIds)
                        {
                            list.Add(new RolePermission() { RoleId = role.RoleId, PermissionId = id });
                        }
                        await _rolePermissionRepository.InsertRangeEntity(list);
                        tran.Complete();
                        return ApiResult.Success();
                    }
                    finally
                    {
                        tran.Dispose();
                    }
                }
            }
            catch (Exception ex)
            {
                _logger.LogError(ex, "Error in InsertRoleCommandHandler" + ex.Message);
                return ApiResult.Failure(ex.Message);
            }
        }
    }
}
